package com.frinder.base.conf;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author frinder
 * @date 2018/8/10
 * @Description:
 */
@Slf4j
@Order(1)
@Component
@Aspect
public class MdcAdvisor {

    /**
     * 所有web下controller
     */
    @Pointcut("execution(* com.frinder..web..*(..))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void beforeAction(JoinPoint joinPoint) {
        try {
            logInfo(log, joinPoint, "=> 1-开始执行");
        } catch (Exception e) {
        }
    }

    @After("pointCut()")
    public void afterAction(JoinPoint joinPoint) {
        try {
            logInfo(log, joinPoint, "<= 1-结束执行");
        } catch (Exception e) {
        }
    }

    private void logInfo(Logger logger, JoinPoint joinPoint, String message) {
        try {
            logger.info("[{}] => 方法[{}.{}] => 参数[{}] => 返回值类型[{}]",
                    message,
                    joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(),
                    JSON.toJSONString(joinPoint.getArgs()),
                    ((MethodSignature) joinPoint.getSignature()).getReturnType()
            );
        } catch (Exception e) {
        }
    }
}
